package com.baidu.ueditor.upload;

import cj.utils.ImageUtils;
import cj.utils.ReadConfigProperties;
import cj.utils.ReturnUUID;

import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.FileType;
import com.baidu.ueditor.define.State;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class BinaryUploader {

	public static final State save(HttpServletRequest request,
			Map<String, Object> conf) {
		FileItemStream fileStream = null;
		boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) != null;

		if (!ServletFileUpload.isMultipartContent(request)) {
			return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
		}

		ServletFileUpload upload = new ServletFileUpload(
				new DiskFileItemFactory());

        if ( isAjaxUpload ) {
            upload.setHeaderEncoding( "UTF-8" );
        }

		try {
			FileItemIterator iterator = upload.getItemIterator(request);

			while (iterator.hasNext()) {
				fileStream = iterator.next();

				if (!fileStream.isFormField())
					break;
				fileStream = null;
			}

			if (fileStream == null) {
				return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
			}

			String savePath = (String) conf.get("savePath");
			String originFileName = fileStream.getName();
			String suffix = FileType.getSuffixByFilename(originFileName);

			long maxSize = ((Long) conf.get("maxSize")).longValue();

			if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
				return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
			}

			// 文件保存路径  
        	String physicalPath2 = ReadConfigProperties.getValue("uploadFilePath");
        	//判断文件是否存在，不存在创建文件
        	Map rep = ReturnUUID.getFolder(physicalPath2);
        	physicalPath2 = rep.get("allpath").toString();//所在的全路径
        	//文件名
            String fileName =  ReturnUUID.getName(originFileName);
            
            savePath += rep.get("filepath").toString()+"/s_"+fileName;

			InputStream is = fileStream.openStream();
			State storageState = StorageManager.saveFileByInputStream(is,
					physicalPath2+"/"+fileName, maxSize);
			is.close();
			
			//------------------------------操作图片	begin
			String imgkzm = ".gif";
			//扩展名(类似:.gif)
            String kzm = ReturnUUID.getFileExt(fileName);
			
			if(!imgkzm.toLowerCase().equals(kzm.toLowerCase())){
				//扩展名不是.gif
//				ImageUtils.scale3(physicalPath2+"/"+fileName, physicalPath2+"/y_"+fileName, 460, 640);// 按比例压缩,做适当截取、图文和图集首图尺寸
//				ImageUtils.scale3(physicalPath2+"/"+fileName, physicalPath2+"/l_"+fileName, 368, 640);// 按比例压缩,做适当截取、头条图尺寸
				ImageUtils.scale4(physicalPath2+"/"+fileName, physicalPath2+"/s_"+fileName, 750);//缩率图		以750宽为基准等比例缩放
//				ImageUtils.scale2(physicalPath2+"/y_"+fileName, physicalPath2+"/ss_"+fileName, 130, 181, true);//缩率图	181*130	图文
//				ImageUtils.scale2(physicalPath2+"/y_"+fileName, physicalPath2+"/sss_"+fileName, 165, 230, true);//缩率图	230*165	图集
			}else{
				//扩展名是.gif
				savePath = (String) conf.get("savePath")+rep.get("filepath").toString()+"/"+fileName;
			}
			//------------------------------操作图片	end

			if (storageState.isSuccess()) {
				storageState.putInfo("url", PathFormat.format(savePath));
				storageState.putInfo("type", suffix);
				storageState.putInfo("original", originFileName);
			}

			return storageState;
		} catch (FileUploadException e) {
			return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
		} catch (IOException e) {
		}
		return new BaseState(false, AppInfo.IO_ERROR);
	}

	private static boolean validType(String type, String[] allowTypes) {
		List<String> list = Arrays.asList(allowTypes);

		return list.contains(type);
	}
}
